import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/log_utils.dart';
import 'package:leader_doctor_flutter/common/utils/string_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/common/widget/verify_code_exception_help.widget.dart';
import 'package:leader_doctor_flutter/router/router.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:netease_meeting_ui/meeting_ui.dart';

class WalletSecurityVerificationPage extends StatefulWidget {
  const WalletSecurityVerificationPage({super.key});

  @override
  State<WalletSecurityVerificationPage> createState() => _WalletSecurityVerificationPageState();
}

class _WalletSecurityVerificationPageState extends State<WalletSecurityVerificationPage> {
  final _smsTextEditingController = TextEditingController();

  int _countValue = 0;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _smsTextEditingController.addListener(() {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    var btnIsSelect = _smsTextEditingController.text.isNotEmpty;
    var showNewNumber = StringUtils.showNewNumber(App.instance.userInfo?.phone);
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: CommWidget.getCommAppbar(context),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            height: 56.w,
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 8.w),
            width: double.infinity,
            child: Text(showNewNumber ?? '',
                style: TextStyle(color: ColorRes.color333333, fontSize: 15.sp, fontWeight: FontWeight.w500)),
          ),
          CommWidget.buildLine(),
          Container(
            height: 56.w,
            padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 8.w),
            width: double.infinity,
            child: Row(
              children: [
                Expanded(
                    child: TextField(
                  controller: _smsTextEditingController,
                  keyboardType: TextInputType.number,
                  inputFormatters: [
                    LengthLimitingTextInputFormatter(6),
                    FilteringTextInputFormatter.allow(RegExp(r'[0-9]'))
                  ],
                  decoration: const InputDecoration(hintText: '请输入验证码', border: InputBorder.none),
                )),
                GestureDetector(
                  onTap: () => _getSms(),
                  child: Container(
                      height: 30.w,
                      padding: EdgeInsets.only(left: 10.w, right: 10.w),
                      alignment: Alignment.center,
                      child: Text(_countValue == 0 ? '获取验证码' : '重新获取（${_countValue}s）',
                          style: TextStyle(
                              fontWeight: FontWeight.w500,
                              color: _countValue == 0 ? ColorRes.colorMain : ColorRes.color9A9A9A,
                              fontSize: 15.sp))),
                )
              ],
            ),
          ),
          CommWidget.buildLine(),
          SizedBox(
            height: 10.w,
          ),
          VerifyCodeExceptionHelpWidget(),
          SizedBox(
            height: 52.w,
          ),
          Padding(
            padding: EdgeInsets.only(left: 16.w, right: 16.w),
            // child: CommWidget.buildBtn('下一步', () => _updatePwdBySmsCode(), isSelect: btnIsSelect),
            child: CommWidget.customBuildBtn("确定", () {
              _updatePwdBySmsCode();
              print("置为灰色 $btnIsSelect");
            }, ColorRes.colorMain, ColorRes.colorB8B3FA, 6.w, isSelect: btnIsSelect),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    // 组件销毁时判断Timer是否仍然处于激活状态，是则取消
    if (_timer?.isActive == true) {
      _timer?.cancel();
    }
    super.dispose();
  }

  /// 启动Timer
  _startTimer() {
    const Duration duration = Duration(seconds: 1);
    cancelTimer();

    _timer = Timer.periodic(duration, (timer) {
      _countValue -= 1;
      Log.d(_countValue);
      if (_countValue <= 0) {
        cancelTimer();
      }
      setState(() {});
    });
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer?.cancel();
    }
  }

  /// 获取验证码
  _getSms() async {
    if (_countValue > 0) return;
    var phone = App.instance.userInfo?.phone;
    if (phone == null || phone.isEmpty == true) return;
    var httpRequest = HttpRequest(Api.sendSms, body: {
      'phone': phone,
      "purpose": 'updateLoginNameVerifyCode',
    });
    var httpResponse = await HttpClient.post(httpRequest);
    var serviceResult = ServiceResult<String?>.simple(httpResponse);
    if (serviceResult.success) {
      _countValue = 60;
      _startTimer();
    }
    ToastUtils.showToast(context, serviceResult.responseMsg);
  }

  /// 下一步
  _updatePwdBySmsCode() async {
    var smsCode = _smsTextEditingController.text;
    if (smsCode.isEmpty) {
      ToastUtils.showToast(context, '请输入验证码');
      return;
    }
    var phone = App.instance.userInfo?.phone;
    var httpRequest = HttpRequest(Api.walletVerifyCode, urlParams: {
      "phoneNum": phone,
      'code': smsCode,
    });
    var httpResponse = await HttpClient.postJson(httpRequest);
    var serviceResult = ServiceResult<dynamic?>.simple(httpResponse);
    print("安全校验 = ${httpResponse.body}");
    if (serviceResult.success) {
      FocusScope.of(context).unfocus();
      context.pushReplacement(PageUrl.walletPwd + '?setPassword=1');
    } else {
      ToastUtils.showToast(context, serviceResult.responseMsg);
    }
  }
}
